<template>
  <div>
    <!-- 动态渲染多个表格 -->
    <div
      v-for="(invoice, index) in invoiceList"
      :key="invoice.invoiceRecogId || invoice.id || invoice.invoiceNum || index"
      class="mb-20"
    >
      <div class="table-title flex items-center justify-between">
        <h3>{{ t('发票信息') }} {{ index + 1 }}</h3>
        <Popconfirm :title="t('是否确认删除该发票？')" @confirm="handleDeleteInvoice(invoice)">
          <!-- v-auth="'bas:sync:edit'" -->
          <a-button type="default">
            <Icon icon="i-simple-line-icons:settings" /> {{ t('删除发票') }}
          </a-button>
        </Popconfirm>
      </div>
      <!--  -->
      <BasicTable
        v-show="(invoice.srmInvoiceRecogRows && invoice.srmInvoiceRecogRows.length) > 0"
        :ref="(el) => setTableRef(el, index)"
        @register="(tableAction) => onTableRegister(tableAction, index)"
        :key="invoice.invoiceRecogId || invoice.id || invoice.invoiceNum || index"
        :columns="tableColumns"
        :rowKey="rowKeyFn"
        :autoCreateKey="false"
        :showTableSetting="false"
        :useSearchForm="false"
        :canResize="false"
        :pagination="false"
        :showIndexColumn="false"
      >
        <template #tableTop>
          <!-- Descriptions -->
          <div class="block m-1 p-2">
            <Descriptions :column="5">
              <Descriptions.Item label="发票代码">{{ invoice.invoiceCode }}</Descriptions.Item>
              <Descriptions.Item label="发票号码">{{ invoice.invoiceNum }}</Descriptions.Item>
              <Descriptions.Item label="发票日期">{{ invoice.invoiceDate }}</Descriptions.Item>
              <!-- 备注，可选 -->
              <Descriptions.Item label="备注">{{ invoice.remarks || '-' }}</Descriptions.Item>
              <Descriptions.Item label="识别状态">
                <DictLabel :dictType="'invoice_status'" :dictValue="invoice.recogStatus" />
              </Descriptions.Item>
            </Descriptions>
            <Descriptions :column="5">
              <Descriptions.Item label="销售方名称">{{ invoice.sellersName }}</Descriptions.Item>
              <Descriptions.Item label="销售方税号">{{
                invoice.sellerRegisterNum
              }}</Descriptions.Item>
              <Descriptions.Item label="购买方名称">{{ invoice.purchaserName }}</Descriptions.Item>
              <Descriptions.Item label="购买方税号">{{
                invoice.purchaserRegisterNum
              }}</Descriptions.Item>
            </Descriptions>
          </div>
          <!-- 可以在这里添加表格顶部内容 -->
        </template>
        <!-- 统一的文本渲染：使用列的命名插槽以匹配 BasicTable 的 bodyCell 逻辑 -->
        <template #textCell="{ text }">
          <span>{{ text }}</span>
        </template>
        <template #footer>
          <!-- 合计信息 -->
          <div class="table-footer">
            <Descriptions
              :column="3"
              :bordered="true"
              :labelStyle="{ width: '120px' }"
              class="mt-10"
            >
              <Descriptions.Item label="合计金额">{{
                formatCurrency(invoice.totalAmount)
              }}</Descriptions.Item>
              <Descriptions.Item label="合计税额">{{
                formatCurrency(invoice.totalTax)
              }}</Descriptions.Item>
              <Descriptions.Item label="价税合计">{{
                formatCurrency(invoice.totalWithTax)
              }}</Descriptions.Item>
            </Descriptions>
          </div>
        </template>
      </BasicTable>
    </div>

  </div>
</template>

<script lang="ts" setup name="ViewsSrmCwInvoiceStep2">
  import { ref, watch, nextTick, inject } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicTable, BasicColumn } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Descriptions, Popconfirm } from 'ant-design-vue';
  import { DictLabel } from '/@/components/Dict';
  import type { InvoiceApi } from '../useInvoiceApi';

  const { t } = useI18n('srm/cw.invoice');
  const { showMessage } = useMessage();
  const invoiceApiRef = inject<import('vue').Ref<InvoiceApi>>('invoiceApi')!;

  const emit = defineEmits(['next', 'prev']);

  // 定义发票数据接口
  interface InvoiceItem {
    id: string;
    rowNum: string;
    cinvname: string;
    cinvspec: string;
    measname: string;
    iqty: string;
    nprice: string;
    nmny: string;
    nictaxrate: string;
    noritaxmny: string;
  }

  interface InvoiceData {
    id: string;
    invoiceCode: string;
    invoiceNum: string;
    invoiceDate: string;
    remarks?: string;
    recogStatus: string;
    sellersName: string;
    sellerRegisterNum: string;
    purchaserName: string;
    purchaserRegisterNum: string;
    invoiceRecogId?: string;
    srmInvoiceRecogRows: InvoiceItem[];
    totalAmount: number;
    totalTax: number;
    totalWithTax: number;
  }

  // 接收父组件传递的数据
  //invoiceParams 从父组件传递过来
  interface InvoiceParams {
    djno: string;
    pkCorp: string;
  }
  const props = defineProps({
    invoiceParams: {
      type: Object as () => InvoiceParams,
      default: () => ({
        djno: '',
        pkCorp: '',
      }),
    },
  });

  // 表格列定义
  const tableColumns: BasicColumn[] = [
    {
      title: t('行号'),
      dataIndex: 'rowNum',
      key: 'rowNum',
      width: 80,
      align: 'center',
      slot: 'textCell',
    },
    {
      title: t('货物或应税劳务名称'),
      dataIndex: 'cinvname',
      key: 'cinvname',
      width: 200,
      align: 'left',
      slot: 'textCell',
    },
    {
      title: t('规格型号'),
      dataIndex: 'cinvspec',
      key: 'cinvspec',
      width: 120,
      align: 'left',
      slot: 'textCell',
    },
    {
      title: t('单位'),
      dataIndex: 'measname',
      key: 'measname',
      width: 80,
      align: 'center',
      slot: 'textCell',
    },
    {
      title: t('数量'),
      dataIndex: 'iqty',
      key: 'iqty',
      width: 100,
      align: 'right',
      slot: 'textCell',
    },
    {
      title: t('无税单价'),
      dataIndex: 'nprice',
      key: 'nprice',
      width: 120,
      align: 'right',
      slot: 'textCell',
    },
    {
      title: t('无税金额'),
      dataIndex: 'nmny',
      key: 'nmny',
      width: 120,
      align: 'right',
      slot: 'textCell',
    },
    {
      title: t('税率'),
      dataIndex: 'nictaxrate',
      key: 'nictaxrate',
      width: 100,
      align: 'right',
      slot: 'textCell',
    },
    {
      title: t('税额'),
      dataIndex: 'noritaxmny',
      key: 'noritaxmny',
      width: 120,
      align: 'right',
      slot: 'textCell',
    },
  ];

  // 发票数据列表
  const invoiceList = ref<InvoiceData[]>([]);

  // 表格引用列表
  const tableRefs = ref<any[]>([]);
  const tableActionsRef = ref<any[]>([]);

  // 设置表格引用
  const setTableRef = (el: any, index: number) => {
    if (el) {
      tableRefs.value[index] = el;
    }
  };

  // 记录各表的 tableAction，便于主动推送数据
  const onTableRegister = (tableAction: any, index: number) => {
    tableActionsRef.value[index] = tableAction;
    // 在注册时立即推送当前已存在的数据，避免时序问题
    const rows = invoiceList.value[index]?.srmInvoiceRecogRows || [];
    tableActionsRef.value[index]?.setTableData?.(rows);
    console.log('onTableRegister', tableActionsRef.value[index], rows, tableActionsRef.value[index].getDataSource().length);
  };

  // 提供稳定的行 key 生成函数，避免内部复用导致不渲染
  const rowKeyFn = (record: InvoiceItem) => record.rowNum || record.id || '';

  // 货币格式化函数
  const formatCurrency = (value: string | number): string => {
    if (!value && value !== 0) return '0.00';
    const num = typeof value === 'string' ? parseFloat(value) : value;
    return num.toFixed(2);
  };

  const formatPercent = (value: string | number): string => {
    if (value === undefined || value === null || value === '') return '';
    return `${value}%`;
  };

  // 计算发票合计
  const calculateInvoiceTotals = (
    srmInvoiceRecogRows: InvoiceItem[],
  ): { totalAmount: number; totalTax: number; totalWithTax: number } => {
    let totalAmount = 0;
    let totalTax = 0;
    srmInvoiceRecogRows.forEach((item) => {
      totalAmount += parseFloat(item.nmny || '0');
      totalTax += parseFloat(item.noritaxmny || '0');
    });
    const totalWithTax = totalAmount + totalTax;
    return {
      totalAmount,
      totalTax,
      totalWithTax,
    };
  };
  // 拉取发票记录并动态组装到多表格
  const fetchInvoiceRecords = async () => {
    try {
      if (!props.invoiceParams?.djno || !props.invoiceParams?.pkCorp) {
        return;
      }
      const res: any = await invoiceApiRef.value.invoiceRecords({
        djno: props.invoiceParams.djno,
        pkCorp: props.invoiceParams.pkCorp,
      });

      const list: any[] = Array.isArray(res) ? res : res?.list || [];
      const invoices: InvoiceData[] = list.map((item: any) => {
        const rawRows: any[] = item.srmInvoiceRecogRows || item.rows || [];
        const rows: InvoiceItem[] = rawRows.map((r: any, idx: number) => ({
          // 确保存在行号，便于作为 rowKey 使用
          rowNum: r.rowNum ?? String(idx + 1),
          id: r.id ?? '',
          cinvname: r.cinvname ?? '',
          cinvspec: r.cinvspec ?? '',
          measname: r.measname ?? '',
          iqty: r.iqty ?? '',
          nprice: formatCurrency(r.nprice),
          nmny: formatCurrency(r.nmny),
          nictaxrate: formatPercent(r.nictaxrate),
          noritaxmny: formatCurrency(r.noritaxmny),
        }));
        const totals = calculateInvoiceTotals(rows);
        return {
          id: item.id || '',
          invoiceCode: item.invoiceCode || '',
          invoiceNum: item.invoiceNum || item.invoiceNo || '',
          invoiceDate: item.invoiceDate || '',
          remarks: item.remarks || '',
          recogStatus: item.recogStatus || '',
          sellersName: item.sellersName || '',
          sellerRegisterNum: item.sellerRegisterNum || '',
          purchaserName: item.purchaserName || '',
          purchaserRegisterNum: item.purchaserRegisterNum || '',
          invoiceRecogId: item.invoiceRecogId || item.id || item.recogId || '',
          srmInvoiceRecogRows: rows,
          ...totals,
        };
      });

      invoiceList.value = invoices;
      await nextTick();

      // 主动把数据推到各 BasicTable，避免初始化时遗漏数据
      invoiceList.value.forEach((inv, idx) => {
        const rows = inv.srmInvoiceRecogRows || [];
        tableActionsRef.value[idx]?.setTableData?.(rows);
        console.log('setTableData-343', rows, tableActionsRef.value[idx]);
      });
    } catch (error) {
      console.error('获取发票记录失败:', error);
      showMessage('获取发票记录失败', 'error');
    }
  };

  // 监听 invoiceList 变化，确保数据与各表同步（处理重建或延迟注册）
  watch(
    invoiceList,
    (list) => {
      list.forEach((inv, idx) => {
        const rows = inv.srmInvoiceRecogRows || [];
        tableActionsRef.value[idx]?.setTableData?.(rows);
        console.log('tableActionsRef-358', rows, idx, tableActionsRef.value[idx], rows.length);
      });
    },
    { deep: true },
  );

  // 监听各表的注册动作引用，注册完成后立即同步当前数据
  watch(
    tableActionsRef,
    (actions) => {
      actions.forEach((action, idx) => {
        const rows = invoiceList.value[idx]?.srmInvoiceRecogRows || [];
        if (action && rows.length) {
          action.setTableData?.(rows);
          console.log('setTableData-371', action, rows);
        }
      });
    },
    { deep: true },
  );

  // 当参数变化时自动拉取（父组件设置好参数后触发）
  watch(
    () => [props.invoiceParams?.djno, props.invoiceParams?.pkCorp],
    async ([djno, pkCorp]) => {
      if (!djno || !pkCorp) return;
      await fetchInvoiceRecords();
    },
    { immediate: true },
  );

  // 仅在进入本步骤或参数变化时拉取数据（由 watch immediate 触发）

  const customResetFunc = () => {
    emit('prev');
  };

  const customSubmitFunc = async () => {
    try {
      // 先进行后端验证，验证上传的发票金额是否匹配单据金额
      const res: any = await invoiceApiRef.value.verifyInvoice({
        djno: props.invoiceParams.djno,
        pkCorp: props.invoiceParams.pkCorp,
      });

      const ok = res?.result === 'true';
      if (!ok) {
        const msg = res?.message || '发票校验未通过，请检查发票金额与单据金额是否一致';
        showMessage(msg, 'error');
        return;
      }

      // 验证通过后，收集所有发票数据并进入下一步
      const allInvoiceData: InvoiceData[] = invoiceList.value;
      emit('next', { invoiceData: allInvoiceData });
    } catch (error) {
      console.error('提交失败:', error);
      showMessage('提交失败，请重试', 'error');
    }
  };

  // 删除当前发票记录
  const handleDeleteInvoice = async (invoice: InvoiceData) => {
    console.log('删除发票：', invoice);
    try {
      const params = {
        djno: props.invoiceParams.djno,
        pkCorp: props.invoiceParams.pkCorp,
        invoiceRecogId: invoice.id,
      };
      const res: any = await invoiceApiRef.value.deleteInvoice(params);
      showMessage(res?.message || '删除成功');
      await fetchInvoiceRecords();
    } catch (error) {
      console.error('删除发票失败:', error);
      showMessage('删除发票失败', 'error');
    }
  };

  // 暴露方法，供父组件触发
  defineExpose({ reload: fetchInvoiceRecords, prev: customResetFunc, next: customSubmitFunc });
</script>

<style scoped>
  .table-title {
    margin-bottom: 10px;
  }
  .table-title h3 {
    color: #1890ff;
    border-left: 4px solid #1890ff;
    padding-left: 10px;
  }
  .block {
    border: 1px solid #d9d9d9;
  }
  .table-footer :deep(.ant-descriptions-item-label) {
    font-weight: bold;
    color: #1890ff;
  }
  .table-footer :deep(.ant-descriptions-item-content) {
    font-weight: bold;
    color: #f5222d;
  }
</style>
